package com.bzxhh.sync;

//1.创建资源类 定义属性和操作方法
class Share {
    //初始值
    private int number = 0;

    //+ method
    public synchronized void incr() throws InterruptedException {
        //2.判断 干活 通知
        while (number != 0) {
            this.wait();
        }
//        if (number != 0) {
//           this.wait();
//        } else if (number == 0) {
//            number++;
//            System.out.println(Thread.currentThread().getName() + " :: " + number);
//        }
        number++;
        System.out.println(Thread.currentThread().getName() + " :: " + number);
        this.notifyAll();
    }

    //- method
    public synchronized void decr() throws InterruptedException {
        while (number != 1) {
            this.wait();
        }
//        if (number != 1) {
//            this.wait();
//        } else if (number == 1) {
//            number--;
//            System.out.println(Thread.currentThread().getName() + " :: " + number);
//        }
        number--;
        System.out.println(Thread.currentThread().getName() + " :: " + number);
        this.notifyAll();
    }
}

public class ThreadDemo1 {
    public static void main(String[] args) {
        Share share = new Share();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "t1").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "t2").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "t3").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "t4").start();

    }
}
